/*
 * @Author: liuxiao
 * @Date: 2023-12-05 01:11:09
 * @Last Modified by: liuxiao
 * @Last Modified time: 2023-12-05 01:12:04
 * @ps:上传控制器，项目所有上传的方法都写在这里
 */

const path = require('path')

const OSS = require('ali-oss')

const { REGION, ACCESSKEYID, ACCESSKEYSECRET, BUCKET } = process.env

const client = new OSS({
  region: REGION,
  accessKeyId: ACCESSKEYID,
  accessKeySecret: ACCESSKEYSECRET,
  bucket: BUCKET
})

const { fileUploadError } = require('../constant/err.type')

class UploadController {
  async upload(ctx, next) {
    //文件上传后,上传的信息被放在ctx.request.files中，
    // console.log(ctx.request.files)

    const { file } = ctx.request.files

    const fileTypes = ['image/jpeg']
    //console.log(file)
    if (file) {
      ctx.body = {
        code: 0,
        message: '商品图片上传成功！',
        data: {
          course_img: path.basename(file.filepath)
        }
      }
    } else {
      return ctx.app.emit('error', fileUploadError, ctx)
    }
    // ctx.body = '课程图片上传'
  }

  //阿里云图片上传
  async aliUpload(ctx, next) {
    //文件上传后,上传的信息被放在ctx.request.files中，
    const { file } = ctx.request.files

    if (file) {
      try {
        let date = new Date()
        let time =
          '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate()
        let filepath = 'course/' + time + '/' + date.getTime()
        let fileext = file.filepath.split('.').pop()
        let newfile = filepath + '.' + fileext

        const res1 = await client.put(newfile, file.filepath)

        //获取带加密签名的图片路径，注意这里的路径不能带有bucket
        //let imgUrl = client.signatureUrl(newfile)
        let imgUrl = res1.url
       // console.log(res1.url)

        // console.log(newfile)
        // const res2 = await client.get(newfile)
        //console.log(res2)

        ctx.body = {
          code: 0,
          message: '课程图片上传成功！',
          data: {
            course_img: imgUrl
          }
        }
      } catch (err) {
        console.log(err)
      }
    } else {
      return ctx.app.emit('error', fileUploadError, ctx)
    }
  }
}

module.exports = new UploadController()
